<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

// 商品管理
class Product extends Backend
{

    protected $model = null;

    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        
        $this->model = model('Product.Product');
        $this->TypeModel = model('Product.Type');
        $this->UnitModel = model('Product.Unit');
    }

    // 商品列表
    public function index()
    {
        //返回筛选数据列表
        $this->assignconfig('unitlist', model("Product.Unit")->column('id,name'));
        $this->assignconfig('typelist', model("Product.Type")->column('id,name'));
        $this->assignconfig('flaglist', model('Product.Product')->flaglist());
        $this->assignconfig('statuslist', model('Product.Product')->statuslist());

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['type','unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['type','unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 添加商品
    public function add()
    {
        if($this->request->isPost())
        {
            // 接收参数
            $params = $this->request->param('row/a');

            if($params)
            {
                $result = $this->model->validate('common/Product/Product')->save($params);

                if($result === FALSE)
                {
                    $thumbs = ltrim($data['thumbs'],'/');

                    @is_file($thumbs) && @unlink($thumbs);

                    $this->error($this->model->getError());
                    exit;
                }else
                {
                    $this->success();
                    exit;
                }
            }
        }

        $this->view->assign('typelist', build_select('row[typeid]', model("Product.Type")->column('id,name'),[], ['class' => 'form-control selectpicker']));

        $this->view->assign('unitlist', build_select('row[unitid]', model("Product.Unit")->column('id,name'),[], ['class' => 'form-control selectpicker']));

        $this->view->assign('flaglist', build_select('row[flag]', model('Product.Product')->flaglist(),[], ['class' => 'form-control selectpicker']));
    
        $this->view->assign('statuslist', build_select('row[status]', model('Product.Product')->statuslist(),[], ['class' => 'form-control selectpicker']));
    

        return $this->view->fetch();
    }

    // 编辑商品
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);

        if(!$row)
        {
            $this->error(__('该商品不存在，请重新选择'));
            exit;
        }

        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            $params['id'] = $ids;

            $result = $this->model->validate('common/Product/Product')->isUpdate(true)->save($params);

            if($result === FALSE)
            {
                if($params['thumbs'] != $row['thumbs'])
                {
                    // 左边的/去掉
                    $thumbs = ltrim($params['thumbs'],'/'); 
                    @is_file($thumbs) && @unlink($thumbs);
                }

                $this->error($this->model->getError());
                exit;
            }else
            {
                // 如果图片名称不一样时说明有更新图片，需要把旧图片删除
                if($params['thumbs'] != $row['thumbs'])
                {
                    $thumbs = ltrim($row['thumbs'],'/');
                    @is_file('.'.$row['thumbs']) && @unlink('.'.$row['thumbs']);
                }

                $this->success();
                exit;
            }
        }

        $this->assign('row', $row);

        $this->view->assign('typelist', build_select('row[typeid]', model("Product.Type")->column('id,name'), $row['typeid'], ['class' => 'form-control selectpicker']));

        $this->view->assign('unitlist', build_select('row[unitid]', model("Product.Unit")->column('id,name'), $row['unitid'], ['class' => 'form-control selectpicker']));

        $this->view->assign('flaglist', build_select('row[flag]', model('Product.Product')->flaglist(), $row['flag'], ['class' => 'form-control selectpicker']));
    
        $this->view->assign('statuslist', build_select('row[status]', model('Product.Product')->statuslist(), $row['status'], ['class' => 'form-control selectpicker']));

        return $this->view->fetch();
    }

    // 软删除
    public function del($ids = null)
    {
        $row = $this->model->select($ids);
        
        if(!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids);

        if ($result === FALSE) 
        {
            $this->error("删除失败");
            exit;
        }else
        {
            $this->success('删除成功');
            exit;
        }
    }

    // 回收站
    public function recyclebin()
    {
        //返回筛选数据列表
        $this->assignconfig('unitlist', model("Product.Unit")->column('id,name'));
        $this->assignconfig('typelist', model("Product.Type")->column('id,name'));
        $this->assignconfig('flaglist', model('Product.Product')->flaglist());
        $this->assignconfig('statuslist', model('Product.Product')->statuslist());

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->onlyTrashed()
                ->with(['type','unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with(['type','unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 还原
    public function restore($ids = NULL)
    {
        //根据id判断数据是否存在
        $rows = $this->model->withTrashed()->whereIn('id', $ids)->select();
        
        if(!$rows)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->restore(['id'=>['in', $ids]]);

        if($result === FALSE)
        {
            $this->error('恢复数据失败');
            exit;
        }else
        {
            $this->success('恢复数据成功');
            exit;
        }
    }

    // 真实删除
    public function destroy($ids = null)
    {
        $row = $this->model->onlyTrashed()->select($ids);

        if (!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids, true);

        if($result === false)
        {
            $this->error($this->model->getError());
            exit;
        }else
        {
            $thumbs = array_column($row, "thumbs");
            $thumbs = array_filter($thumbs);
            $thumbs = array_unique($thumbs);

            if(!empty($thumbs))
            {
                foreach($thumbs as $item)
                {
                    $item = ltrim($item,'/');
                    @is_file($item) && @unlink($item);
                }
            }
            
            $this->success();
            exit;
        }
    }
}